﻿using System.Linq;
using System.Web.Mvc;

namespace MvcSupplantCaching
{
    /// <summary>
    /// Extension methods for the ActionExecutingContext class.
    /// </summary>
    public static class ActionExecutingContextExtensions
    {
        /// <summary>
        /// Gets the output cache key for the current action that is executing.
        /// </summary>
        /// <param name="filterContext">The context to use for getting the cache key.</param>
        /// <returns>The cache key that will be used for caching this page.</returns>
        public static string GetOutputCacheKey(this ActionExecutingContext filterContext)
        {
            var attribute = filterContext.GetCacheAttribute();
            return attribute != null ? attribute.GetCacheKeyForController(filterContext) : null;
        }

        /// <summary>
        /// Gets the SupplantOutputCacheAttribut for the current action that is executing.
        /// </summary>
        /// <param name="filterContext">The context to use for getting the attribute.</param>
        /// <returns>The SupplantCacheAttribute in use on the currently executing action.</returns>
        public static ISupplantOutputCacheAttribute GetCacheAttribute(this ActionExecutingContext filterContext)
        {
            var outputCacheAttributeObjects = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ISupplantOutputCacheAttribute), true);
            ISupplantOutputCacheAttribute attribute = outputCacheAttributeObjects.FirstOrDefault() as ISupplantOutputCacheAttribute;
            if (attribute != null)
            {
                return attribute;
            }
            return null;
        }
    }
}
